package com.bw.gmall.realtime.app.zyjdwd;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.utils.DateFormatUtil;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;

public class Zyj_DwdTrafficUniqueVisitorDetail {

    public static void main(String[] args) throws Exception {

        // TODO 1. 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        String topic = "dwd_traffic_page_log";
        String groupId = "dwd_traffic_user_jump_detail";
        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId);
        DataStreamSource<String> pageLog = env.addSource(kafkaConsumer);
//        pageLog.print() ;
        // TODO 2. 状态后端设置
        SingleOutputStreamOperator<JSONObject> flatMap = pageLog.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObj = JSON.parseObject(value);
                    out.collect(jsonObj);
                } catch (Exception e) {
                    System.out.println("脏数据:" + value);
                }
            }
        });
        SingleOutputStreamOperator<JSONObject> filternull = flatMap.filter(a -> a.getJSONObject("page").getString("last_page_id") == null);
        KeyedStream<JSONObject, String> keyedStream = filternull.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));
        SingleOutputStreamOperator<Object> process = keyedStream.process(new KeyedProcessFunction<String, JSONObject, Object>() {
            private ValueState<String> lastVisitDt;

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<String>("last_visit_dt", String.class);
                valueStateDescriptor.enableTimeToLive(StateTtlConfig.
                        newBuilder(Time.days(1L))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build());
                lastVisitDt = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, Object>.Context ctx, Collector<Object> out) throws Exception {
                Long ts = value.getLong("ts");
                String s = DateFormatUtil.toDate(ts);
                String lastDt = lastVisitDt.value();
                if (lastDt == null || !lastDt.equals(s)) {
                    lastVisitDt.update(s);
                    out.collect(value);
                }
            }
        });
        process.print("=================>独立访客");
        env.execute();
    }
}
